import { ready, assert } from '@/lib/utils';
import { get } from '@/lib/request';
import { handleFileAction } from '@/lib/file';
import { addFileIconToElem } from '@/lib/file-icon';

function setupRequestAccessResumeButton() {
    const elems = document.querySelectorAll("[data-request-access-btn]");
    elems.forEach((elem) => {
        const trElem = elem.closest("tr")!;
        const file_uuid = trElem.getAttribute("data-resume-uuid")!;
        
        (elem as HTMLElement).addEventListener("click", async () => {
            try {
                const response = await get(`/api/media/request_access/${file_uuid}`);
                alert(await response.text());
            } catch (error) {
                // already implemented in `get` function ...
            }
        });
    })
}

function setupDownloadResumeButton() {
    const elems = document.querySelectorAll("[data-download-resume-btn]");
    elems.forEach(elem => {
        const trElem = elem.closest("tr")!;
        const file_uuid = trElem.getAttribute("data-resume-uuid")!;
        const filename = trElem.getAttribute("data-resume-filename")!;
        
        (elem as HTMLElement).addEventListener("click", () => {
            handleFileAction(`/media/raw/${file_uuid}`, filename);
        });
    });
}

function setupFileNameCol() {
    const elems = document.querySelectorAll("[data-filename-col]");
    elems.forEach((elem) => {
        const trElem = elem.closest("tr")!;
        const filename = trElem.getAttribute("data-resume-filename")!;
        const content_type = trElem.getAttribute("data-resume-content-type")!;
        addFileIconToElem(elem as HTMLElement, {
            filename: filename,
            contentType: content_type,
            iconClass: "tw:size-4"
        })
    });
}

(function () {
    ready(() => {
        setupRequestAccessResumeButton();
        setupDownloadResumeButton();
        setupFileNameCol();
    });
})();
